﻿using System;
using System.Collections.Generic;
using System.Linq;
using ZilLion.TaskManager.Core.Quartz;
using ZilLion.TaskManager.Entity.Entity;

namespace ZilLion.TaskManager.Core.TaskRunTime.Exe
{
    [Serializable]
    public class TaskExeRuntime : MarshalByRefObject
    {
        /// <summary>
        ///     正在执行的task
        /// </summary>
        public IList<TaskConfig> ExcutingTasks { get; } = new List<TaskConfig>();


        public ExeSchedulerContainer ExeSchedulerContainer { get; set; }

        /// <summary>
        ///     开始任务
        /// </summary>
        /// <param name="config"></param>
        /// <param name="taskModuleConfig"></param>
        /// <returns></returns>
        public void StartTask(TaskConfig config, TaskModuleConfigEntity taskModuleConfig)
        {
            var first = ExcutingTasks.FirstOrDefault(x => x.Taskid == config.Taskid);
            if (first == null)
                ExcutingTasks.Add(config);
            ExeSchedulerContainer.GetContainerInstance().StartTask(config);
        }

        /// <summary>
        ///     暂停任务
        /// </summary>
        /// <returns></returns>
        public void PauseTask(TaskConfig config)
        {
            var first = ExcutingTasks.FirstOrDefault(x => x.Taskid == config.Taskid);
            if (first != null)
                ExcutingTasks.Remove(config);
            ExeSchedulerContainer.GetContainerInstance().PauseTask(config);
        }

        ///// <summary>
        /////     卸载任务
        ///// </summary>
        ///// <param name="config"></param>
        ///// <returns></returns>
        public bool DeleteTask(TaskConfig config)
        {
            var first = ExcutingTasks.FirstOrDefault(x => x.Taskid == config.Taskid);
            if (first != null)
                ExcutingTasks.Remove(config);
            ExeSchedulerContainer.GetContainerInstance().DeleteTask(config);

            return true;
        }

        /// <summary>
        ///     释放任务资源
        /// </summary>
        /// <returns></returns>
        public bool UninstallSchedule()
        {
            ExcutingTasks.Clear();
            ExeSchedulerContainer.StopSchedule();
            return true;
        }

        #region 单例

        private static volatile TaskExeRuntime _instance;
        private static readonly object Lock = new object();

        private TaskExeRuntime()
        {
        }


        public static TaskExeRuntime GetInstance()
        {
            if (_instance == null)
                lock (Lock)
                {
                    _instance = new TaskExeRuntime
                    {
                        ExeSchedulerContainer = ExeSchedulerContainer.GetContainerInstance()
                    };

                    _instance.ExeSchedulerContainer.StartScheduler();
                }
            return _instance;
        }

        #endregion
    }
}